/* ------------------------------------------------------------------------*
 *
 * ------------------------------------------------------------------------*/

#include "bsp.h"
#include "pincfg.h"
#include "os_obj.h"
#include "mbapp.h"
#include "com_def.h"
#include "bsp_cpu_it.h"
#include "bsp_uart_timer.h"
#include "pincfg.h"
//针对IO模块，超时改为50ms
//RS3
#define mbPORT UART3
#define mbURT_IRQn UART3_IRQn
#define mbISR MB_UART3_IRQHandler
#define mbObj mb.obj03
#define mbCmdBuff mb.CmdBuff03

//RS485 Dir-Pin
#define mbRxEnable()
#define mbTxEnable()

#include "bsp_mbport_gen.c"
#include "mb_fun.h"

/*****************************************************************************
* @brief   mb port.
* @param   none
* @return  none
* @ Pass/ Fail criteria: none
*****************************************************************************/
static void mb_port_hal_cfg(void)
{
	intx_alloc();

	nvic_irq_set(mbURT_IRQn, 0x0F, 0);

	intx_disable();

	RCC_APB2_Peripheral_Clock_Enable(RCC_APB2_PERIPH_UART3);

	intx_enable();
}

/*****************************************************************************
* @brief   mb_cb_set
* @param   none
* @return  none
* @ Pass/ Fail criteria: none
*****************************************************************************/
static void mb_cb_set(void)
{
	intx_alloc();

	mbObj.slave.reg_coils_cb = &smb_reg_coils_cb;
	mbObj.slave.reg_discrete_cb = &smb_reg_discrete_cb;
	mbObj.slave.reg_hold_cb = &smb_reg_holding_cb;
	mbObj.slave.reg_input_cb = &smb_reg_input_cb;

	mmb_cmd_buff_init(&mbObj, mbCmdBuff, sizeof(mbCmdBuff)/sizeof(mbCmdBuff[0]), 16);

	intx_disable();

	mbObj.api = &mb_fun;

	intx_enable();
}

/*****************************************************************************
* @brief   mb init .
* @param   mbMode
* @param   ulBaudRate
* @param   eParity
* @return  none
* @ Pass/ Fail criteria: none
*****************************************************************************/
void mb03_Init(mb_mode_type mbMode, uint32_t ulBaudRate, mb_parity_type eParity)
{
	// 禁用中断
	nvic_irq_set(mbURT_IRQn, 0x0F, 0);
	uart_timer.uart3 = 0;

	// 中断映射
	cpu_it.uart3 = mbISR;

	// 初始化
	mb_port_Init(mbMode, ulBaudRate, eParity);

	// 链接定时器任务
	uart_timer.uart3 = _rtu_timer_run;
	app_timer_task_add(uart3_timer_handle);
}
